package com.central.apps.handler.contract;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.base.BaseHandler;
import com.central.app.controller.FlowCommonController;
import com.central.app.dao.BizFlowAppDao;
import com.central.app.model.BizFlowApp;
import com.central.app.service.HandlerService;
import com.central.apps.controller.PoiController;
import com.central.apps.entity.CostAttribute;
import com.central.apps.handler.until.DateUtiles;
import com.central.apps.service.CostOccupyService;
import com.central.apps.util.StringUtil;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.exception.service.ServiceException;

import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ConapplicationHandler extends BaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private ConsignsHandler consignsHandler;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Autowired
    private CostOccupyService costOccupyService;
    @Autowired
    private ConchangeHandler conchangeHandler;
    @Autowired
    private ConreviewHandler conreviewHandler;
    @Autowired
    private FlowCommonController flowCommonController;
    @Autowired
    private PoiController poiController;
    @Autowired
    private BizFlowAppDao flowAppDao;
    @Autowired
    private ConUtil conUtil;

    //流程审批前，判断交付物
    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        System.out.println("测试审批前逻辑是否执行==================" + flowNode.getId());
        //提交审批前
        if ("submit".equals(flowNode.getId())) {
            System.out.println("===============进入查询代码===================");
            //校验是否添加了对方单位
            List<Map<String, Object>> list3 = handlerService.findBySql("select conid,isframecon from gq_conapplication where id = " + id);
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_coordinationinfo where conid=" + list3.get(0).get("conid"));
            //审批前，将值恢复成默认值。兼容被驳回后重新审批走流程过程
            System.out.println("被驳回后恢复默认值状态");
            Map<String, Object> map = new HashMap<>();
            map.put("id", id);
            map.put("isreasonable", "");
            map.put("isclear", "");
            map.put("neandfe", "");
            map.put("technology", "");
            map.put("supplierin", "");
            map.put("isbudget", "");
            map.put("isreview", "");
            map.put("reviewtype", "");
            map.put("istypereasonable", "");
            map.put("isonline", "");
            map.put("istechnology", "");
            //map.put("ispublicity","");
            map.put("publicity", "");
            map.put("agreeoutsourcing", "");

            map.put("fundguarantee", "");
            map.put("declarecomplete", "");
            map.put("ismaterial", "");
            map.put("bringinto", "");
            handlerService.update("gq_conapplication", map);
            if (CollectionUtils.isEmpty(list)) {
                return "请添加对方单位信息之后再提交审批";
            }
            //如果是框架合同，验证是否增加了物料明细
            //新逻辑，所有合同，都必须增加物料明细
            //if("是".equals(list3.get(0).get("isframecon"))){
            List<Map<String, Object>> list2 = handlerService.findBySql("select id from gq_conpoline where conid=" + list3.get(0).get("conid"));
            if (CollectionUtils.isEmpty(list2)) {
                return "需要添加物料明细再提交审批";
            }
            // }
            // 校验成本是否满足合同申请
            try {
                return validateCost(op.getVariables());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //主管部门审查前---去掉逻辑控制
//        if ("approval0201".equals(flowNode.getId())) {
//            //如果是线上评审，需要增加评审人员
//            List<Map<String, Object>> list3 = handlerService.findBySql("select isonline,conid from gq_conapplication where id = " + id);
//            if ("是".equals(list3.get(0).get("isonline"))) {
//                String conid = (String) list3.get(0).get("conid");
//                //1.查询评审组成员
//               // List<Map<String, Object>> list = handlerService.findBySql("select username from gq_reviewmember where conid = " + id);
//                //2.专家组成员
//                List<Map<String, Object>> list2 = handlerService.findBySql("select username from gq_expertgroup where conid = " + conid);
//                //StringBuffer names = new StringBuffer();
//                if (CollectionUtils.isEmpty(list2)) {
//                    return "选择线上评审后，需要添加评审人员信息在提交审批";
//                }
//            }
//        }


        //审批后逻辑移动到此处

        if (flowNode.getId().equals("approval03")) {
            boolean flag = op.isFlag();
            if (flag) {
                String sql = "select * from  gq_conapplication where id = " + id;
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                String createuser = MapUtils.getString(list.get(0), "createuser");
                String createuserdesc = MapUtils.getString(list.get(0), "createuserdesc");
                String deptcode = MapUtils.getString(list.get(0), "deptcode");
                String conname = MapUtils.getString(list.get(0), "conname");//合同名称
                String deptName = MapUtils.getString(list.get(0), "deptcodeEntity_fullname");//申请单位名称
                String totalprice = MapUtils.getString(list.get(0), "totalprice");//合同金额
                String secondname = setTwo(id);//供方名称
                String subjectno = MapUtils.getString(list.get(0), "subjectno");//课题号

                String totalprices = StringUtil.setDouble(MapUtils.getDoubleValue(list.get(0), "totalprice"));//合同金额保留两位小数

//                String sql = "select * from  gq_conapplication where id = " + id;
//                List<Map<String, Object>> list = handlerService.findBySql(sql);
                int conid = 0;
                if (CollectionUtils.isNotEmpty(list)) {
                    for (Map<String, Object> objectMap : list) {
                        //通过插入合同台账
                        Map<String, Object> map = new HashMap<>();
                        map.put("concode", objectMap.get("concode"));//合同编号
                        map.put("conname", objectMap.get("conname"));//合同名称
                        map.put("contemplate", objectMap.get("contemplate"));//合同模板编号
                        map.put("applicant", objectMap.get("applicant"));//申请人编号
                        map.put("level", objectMap.get("level"));//级别
                        map.put("deptcode", objectMap.get("deptcode"));//申请部门
                        map.put("applytime", objectMap.get("applytime"));//申请日期
                        map.put("protype", objectMap.get("protype"));//采购方式
                        map.put("applycompany", objectMap.get("applycompany"));//申请单位编号
                        map.put("applicantEntity_name", objectMap.get("applicantEntity_name"));//申请人
                        map.put("applycompanyEntity_fullname", objectMap.get("applycompanyEntity_fullname"));//申请单位
                        map.put("relationprocodeEntity_proname", objectMap.get("relationprocodeEntity_proname"));
                        map.put("taskidEntity_name", objectMap.get("taskidEntity_name"));
                        map.put("conterm", objectMap.get("endtime"));//合同期限
                        map.put("supplier", objectMap.get("supplier"));//供方名称
                        map.put("outsourcingtype", objectMap.get("outsourcingtype"));//外协类型
                        map.put("rationality", objectMap.get("rationality"));//外协主要内容及合理性
                        map.put("conlevel", objectMap.get("conlevel"));//合同密级
                        map.put("totalprice", objectMap.get("totalprice"));//合同金额（含税）
                        map.put("objtype", objectMap.get("objtype"));//项目类型
                        map.put("unitleader", objectMap.get("unitleader"));//单位领导
                        map.put("title", objectMap.get("title"));//标题
                        map.put("createuser", createuser);//创建人编号
                        map.put("createuserdesc", createuserdesc);//创建人名称
                        map.put("conuser", objectMap.get("createuserdesc"));//合同经办人
                        // 目前有俩合同类型ヽ(´¬`)ノ
                        map.put("contracttype", objectMap.get("contracttype"));//合同类型
                        map.put("typecode", objectMap.get("typecode"));//合同类型编号
                        map.put("isframecon", objectMap.get("isframecon"));//是否为框架合同
                        map.put("maincon", objectMap.get("maincon"));//关联合同编号
                        map.put("oppcompany", secondname);//对方单位名称
                        map.put("iscollcon", objectMap.get("iscollcon"));//合同类别
                        map.put("subjectno", subjectno);//课题号
                        map.put("isconsign", objectMap.get("isconsign"));//是否简易合同
                        map.put("untotalprice", objectMap.get("untotalprice"));//可分配金额--目前暂没有用到
                        //String sql1 = "select conid from gq_conaccount order by conid desc limit 1";
                        //List<Map<String, Object>> aclist = handlerService.findBySql(sql1);
                        //String conidd = (String) objectMap.get("conid");
                        conid = Integer.valueOf(MapUtils.getString(objectMap, "conid"));
                        map.put("conid", conid);//合同序号
                        //将上传的文件插入到合同台账的
                        //如果不需要评审，同步到台账，如果需要评审，不需要同步到合同台账，名称加一个标志，表示从合同申请过来的
                        if ("否".equals(MapUtils.getString(objectMap, "isreview"))) {
                            map.put("constatus", "待签订");
                        } else {
                            map.put("constatus", "待评审");
                        }

                        handlerService.insert("gq_conaccount", map);
                        //合同签订完，状态改为已签订
                        //conchangeHandler.updateStatusByid(id, "已申请");
                        //修改合同状态
                        //Map<String, Object> map = new HashMap<>();
                        try {
                            map.put("id", id);
                            String isreview = MapUtils.getString(list.get(0), "isreview");
                            if ("是".equals(isreview)) {
                                map.put("constatus", "待评审");
                            } else {
                                map.put("constatus", "待签订");
                                //如果不需要评审，把合同申请的合同文本同步到台账，如果需要评审，合同评审完毕后，合同评审那边把合同文本同步到合同台账
                                fileSynUtilService.insertFiles(app, id, conid, null);
                            }
                            try {
                                //将合同申请提炼出概要数据，赋值给概要字段
                                String summary = addsummary(id);
                                map.put("summary", summary);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            //map.put("constatus","已申请");
                            handlerService.update("gq_conapplication", map);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //try {
                        String isreview = MapUtils.getString(objectMap, "isreview");
                        if ("是".equals(isreview)) {
                            map.put("isonline", objectMap.get("isonline"));//是否线上评审
                            map.put("firstname", objectMap.get("applycompanyEntity_fullname"));
                            map.put("reviewtype", objectMap.get("reviewtype"));//评审方式
                            map.put("ispublicity", objectMap.get("ispublicity"));//是否公示
                            map.put("publicity", objectMap.get("publicity"));//公示天数
                            map.put("secondname", secondname);//乙方名称
                            map.put("cosid", objectMap.get("cosid"));//
                            map.put("endtime", objectMap.get("endtime"));//合同结束时间
                            map.put("reviewmoney", objectMap.get("totalprice"));//评审经费==合同金额
                            map.put("constatus", "待评审");
                            map.put("applyid", id);
                            map.put("nconname", objectMap.get("conname"));
                            map.put("conreviewsnum", ("CDCR" + conid));
                            map.put("isconsign", objectMap.get("isconsign"));//是否简易订单
                            addconconreviews(map);
                        }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    }


                    //流程归档
                    fileSynUtilService.processarc(app, id + "", "合同申请", (String) list.get(0).get("concode"), (String) list.get(0).get("conname"));
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    String ispublicity = (String) list.get(0).get("ispublicity");//是否公示

                    if ("是".equals(ispublicity)) {
                        //conchangeHandler.updateStatus((String) list.get(0).get("concode"), "公示中");
                        conchangeHandler.updateStatusByConid(conid, "公示中");
                        //设置公示结束时间 ,公示期中的申请页面不许修改，只能查看
                        //int publicity = (int) list.get(0).get("publicity");
                        int publicity = 3;
                        //公示天数改成从业务配置里边获取
                        List<Map<String, Object>> list2 = handlerService.findBySql("select paramvalue from gq_pcline where paramcode = 'publicity'");
                        if (CollectionUtils.isNotEmpty(list2)) {
                            publicity = MapUtils.getIntValue(list2.get(0), "paramvalue");
                        }
                        Date publicityend = DateUtiles.stepDay(new Date(), publicity);
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", id);
                        map.put("constatus", "公示中");
                        map.put("publicity", publicity);
                        map.put("publicityend", publicityend);

                        handlerService.update("gq_conapplication", map);
                        String title = conname + "-合同公示";
                        StringBuffer sb = new StringBuffer();
                        //String content = "合同名称：" + conname + ";合同申请单位：" + deptName + ";合同金额：" + totalprices + ";供方名称：" + secondname + ";";
                        sb.append("合同名称：" + conname);
                        sb.append("\r\n");
                        sb.append("合同申请单位：" + deptName);
                        sb.append("\r\n");
                        sb.append("合同金额：" + totalprices);
                        sb.append("\r\n");
                        sb.append("供方名称：" + secondname);
                        //添加到公告表中
                        setNotice(title, publicityend, sb.toString());
                    }

                }
                try {
                    // 组织成本属性对象
                    CostAttribute costAttribute = combineCostAttribute(op.getVariables());
                    // 调用成本占用方法
                    costOccupyService.costOccupyRelease(costAttribute, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //如果是框架合同的子合同，物料数量同步到框架合同中的已订货数
                int conpid = MapUtils.getIntValue(list.get(0), "conpid");//框架合同主键id
                int cconid = MapUtils.getIntValue(list.get(0), "cconid");//框架合同序号
//                int conid = MapUtils.getIntValue(list.get(0), "conid");//子合同序号
//                int cconid = MapUtils.getIntValue(list.get(0), "cconid");//框架合同序号
                List<Map<String, Object>> lists = handlerService.findBySql("select orderqty,itemnum from gq_conpoline where conid=" + conid + " and conpid =" + id);
                for (Map<String, Object> stringObjectMap : lists) {
                    int orderqty = 0;//子表物质数量
                    if (ToolUtil.isNotEmpty(stringObjectMap.get("orderqty"))) {
                        orderqty = MapUtils.getIntValue(stringObjectMap, "orderqty");
                    }
                    List<Map<String, Object>> listss = handlerService.findBySql("select ordered ,id,unordered from gq_conpoline where conid=" + cconid + " and conpid =" + conpid + " and" +
                            " itemnum = '" + stringObjectMap.get("itemnum") + "'");
                    if (CollectionUtils.isNotEmpty(listss)) {
                        int ordered = 0;//框架合同中物质已订货数量
                        int unordered = 0;
                        int ids = MapUtils.getIntValue(listss.get(0), "id");
                        if (ToolUtil.isNotEmpty(listss.get(0).get("ordered"))) {
                            ordered = MapUtils.getIntValue(listss.get(0), "ordered");//已订货数
                        }
                        if (ToolUtil.isNotEmpty(listss.get(0).get("unordered"))) {
                            unordered = MapUtils.getIntValue(listss.get(0), "unordered");//待订货数
                        }
                        ordered = ordered + orderqty;
                        unordered = unordered - orderqty;
                        handlerService.updateBySql("update gq_conpoline set ordered =" + ordered + ",unordered = " + unordered + "  where id = " + ids);
                    }

                }
                //更新框架合同剩余金额
                try {
                    handlerService.updateBySql("update gq_conapplication set untotalprice=untotalprice-" + totalprice + "  where id = " + conpid);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                //审批通过后，如果是子合同，自动生成订单
                //针对于框架合同中的子合同，自动生成外协订单
                //if(ToolUtil.isNotEmpty(list.get(0).get("maincon"))){
                //非框架合同，只要是带有物料明细的合同，都自动创建外协订单
                //0715 框架合同也要生成订单，只是不显示
                //if(!"是".equals(list.get(0).get("isframecon"))) {
                setPoInfo(id);
                //}
                // }
                //框架合同，物料明细添加到物料主数据中
//                if("是".equals(list.get(0).get("isframecon"))){
//                    setPoInfo(id);
//                }
            }


        }
        return "";
    }

    //审批通过后，物料数据添加到物料主数据中
    public void setItem(long id) throws Exception {
        Map<String, Object> conapplication = handlerService.findOneBySql("select * from gq_conapplication where id= " + id);

    }

    //审批通过后，如果是子合同，自动生成订单
    public void setPoInfo(long id) throws Exception {
        List<Map<String, Object>> list = handlerService.findBySql("select * from gq_conapplication where id= " + id);
        if (CollectionUtils.isNotEmpty(list)) {
            //子表信息添加
            int conid = MapUtils.getIntValue(list.get(0), "conid");
            int conpid = MapUtils.getIntValue(list.get(0), "id");//合同申请主键id
            int cconid = MapUtils.getIntValue(list.get(0), "cconid");//框架合同序号
            int cconpid = MapUtils.getIntValue(list.get(0), "conpid");//框架合同主键id
            String applicationnum = MapUtils.getString(list.get(0), "applicationnum");//合同申请编号
            String agreeoutsourcing = MapUtils.getString(list.get(0), "agreeoutsourcing");//是否同意外协
            String isframecon = MapUtils.getString(list.get(0), "isframecon");//是否框架合同
            String isconsign = MapUtils.getString(list.get(0), "isconsign");//是否简易订单
            String isreview = MapUtils.getString(list.get(0), "isreview");//是否评审
            //查询合同申请中的物料明细

            //有物料明细并且同意外协为是 的情况下生成外协订单,  //0715 先不要这个逻辑

            //if(CollectionUtils.isNotEmpty(list2)&&"是".equals(agreeoutsourcing)){
            //查询合同申请中的供应商信息
            String suppliername = "";
            String supplierno = "";
            //查询子表供应商
            List<Map<String, Object>> lists = handlerService.findBySql("select companyname ,supplierno from gq_coordinationinfo where conid = " + list.get(0).get("conid"));
            if (CollectionUtils.isNotEmpty(lists)) {
                suppliername = MapUtils.getString(lists.get(0), "companyname");
                supplierno = MapUtils.getString(lists.get(0), "supplierno");
            }
            //主表信息添加
            Map<String, Object> map = new HashMap<>();
            map.put("description", list.get(0).get("conname"));//订单名称
            //不签订合同，也就是子合同，直接赋值框架合同的供应商信息// 这个值改成了是否简易订单
            if ("是".equals(isconsign)) {
                map.put("suppliername", suppliername);//供应商
                map.put("suppliernum", supplierno);//供应商编号
            }
            //map.put("suppliername",suppliername);//供应商 --合同签订完后再给供应商赋值
            //map.put("suppliernum",supplierno);//供应商编号
            map.put("billtoattn", list.get(0).get(""));//接收人编号
            //map.put("requireddate",list.get(0).get("applicantEntity_name"));//计划接收人
            map.put("applicationnum", list.get(0).get("applicationnum"));//合同申请编号
            map.put("conname", list.get(0).get("conname"));//合同名称
            map.put("totalprice", list.get(0).get("totalprice"));//合同金额
            map.put("contype", list.get(0).get("contracttype"));//合同类型
            //map.put("unpaidamts",list.get(0).get("totalprice"));//合同金额==未开发票金额
            map.put("unpaidamt", list.get(0).get("totalprice"));//合同金额==未开发票金额
            map.put("conpid", list.get(0).get("id"));//合同申请主键id
            map.put("conid", list.get(0).get("conid"));//合同申请需要
            map.put("cconid", list.get(0).get("cconid"));//框架合同序号
            map.put("cconpid", list.get(0).get("conpid"));//框架合同主键id
            map.put("requireddate", list.get(0).get("requireddate"));//收货日期
            map.put("createuser", MapUtils.getString(list.get(0), "createuser"));//创建人编号
            map.put("createuserdesc", MapUtils.getString(list.get(0), "createuserdesc"));//创建人名称
            map.put("subjectno", list.get(0).get("subjectno"));//课题号
            map.put("proid", list.get(0).get("proid"));//项目主键id
            map.put("proname", list.get(0).get("proname"));//项目名称
            map.put("purchasetype", list.get(0).get("protype"));//采购方式
            //map.put("unpaidamts", MapUtils.getString(list.get(0),"createuserdesc"));//创建人名称

            map.put("isconsign", isconsign);//是否简易订单
            Map<String, Object> poMap = new HashMap<>();
            BigInteger poid = null;
            try {
                //判断订单是否显示
                if ("否".equals(isframecon) && "是".equals(isconsign) && "否".equals(isreview)) {
                    map.put("isshow", "是");
                } else {
                    map.put("isshow", "否");
                }

                handlerService.addBizNum("poApp", "gq_po", poMap);
                System.out.println("采购订单编号===========" + poMap.get("ponum"));
                map.put("ponum", poMap.get("ponum"));
                poid = (BigInteger) handlerService.insert("gq_po", map);
                //把订单号同步到合同台账
                try {
                    handlerService.updateBySql("update gq_conaccount set ponum = '"+poMap.get("ponum")+"' where conid ="+conid);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            //查询合同申明物料明细，插入到外协订单物料明细
            List<Map<String, Object>> list2 = handlerService.findBySql("select * from gq_conpoline where conid =" + conid + " and conpid=" + conpid);
            for (Map<String, Object> stringObjectMap : list2) {
                stringObjectMap.put("ponum", poMap.get("ponum"));//外协订单编号
                stringObjectMap.put("poid", poid);//外协订单主键id
                stringObjectMap.put("cconid", cconid);
                stringObjectMap.put("cconpid", cconpid);
                stringObjectMap.put("applicationnum", applicationnum);//合同申请编号
                stringObjectMap.put("linecost", stringObjectMap.get("totalcost"));//金额

                try {
                    handlerService.insert("gq_poline", stringObjectMap);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                //明细行物料添加到物料主数据
//                    Map<String, Object> itemMap = new HashMap<>();
//                    handlerService.addBizNum("itemApp", "gq_item", itemMap);
//                    stringObjectMap.put("itemnum",itemMap.get("itemnum"));
//                    handlerService.insert("gq_item",stringObjectMap);
            }

            //自动提交流程，审批
            try {
                String app = "conpoApp";
                flowCommonController.startFlow(app, poid.longValue());

                FlowOpinion op = new FlowOpinion();
                op.setOpinion("同意");
                Map<String, Object> objmap = new HashMap<>();
                objmap.put("direction", "1");
                flowCommonController.completeFlow(app, poid.longValue(), op, objmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //  }

    }

    //将合同申请概要内容添加到概要字段
    public String addsummary(long id) {
        String summary = "";
        List<Map<String, Object>> list = handlerService.findBySql("select protype,applicantEntity_name,rationality from gq_conapplication where id= " + id);
        //采购方式
        String protype = MapUtils.getString(list.get(0), "protype");//采购方式
        String applicant = MapUtils.getString(list.get(0), "applicantEntity_name");//申请人
        String rationality = MapUtils.getString(list.get(0), "rationality");//外协主要内容及合理性
        StringBuffer sb = new StringBuffer();
        sb.append("采购方式：").append(protype);
        sb.append("; 申请人：").append(applicant);
        sb.append("\r\n");
        sb.append("外协主要内容及合理性：").append(rationality);
        summary = sb.toString();
        return summary;
    }

    //合同申请完毕后，自动添加到合同评审中的会签环节
    public void addconconreviews(Map<String, Object> map) throws Exception {
        //try {
        long fromId = MapUtils.getLong(map, "id");
        map.put("id", null);
        handlerService.insert("gq_conreviews", map);
        //long id = 0l;
        LoginAppUser loginuser = SysUserUtil.getLoginAppUser();

        List<Map<String, Object>> list = handlerService.findBySql("select id from  gq_conreviews where conid = " + map.get("conid"));
        long id = MapUtils.getLongValue(list.get(0), "id");
        System.out.println("===========主键id=======" + list.get(0).get("id"));
        Map<String, Object> map1 = new HashMap<>();
        map1.put("id", id);
        map1.put("approve", loginuser.getField10());
        System.out.println("approve===========" + loginuser.getUsername());
        handlerService.update("gq_conreviews", map1);
        String app = "conreviewsApp";
        flowCommonController.startFlow(app, id);

        FlowOpinion op = new FlowOpinion();
        op.setOpinion("同意");
        Map<String, Object> objmap = new HashMap<>();
        objmap.put("direction", "1");
        BizFlowApp flowApp = flowAppDao.findByAppAndBizId(app, id + "");
        flowCommonController.completeFlow(app, id, op, objmap);


//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000 * 10);//1秒
//                    flowCommonController.completeFlow(app, id, op, objmap);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }.start();

        List<Map<String, Object>> list5 = handlerService.findBySql("select conid,applyid from gq_conreviews where id = " + id);
        //String sql = "select id from gq_conapplication where conid = "+list.get(0).get("conid");
        //Long fromId =id;//合同申请主表id
        //过程资料附件
        conreviewHandler.fileremove("conapplicationApp", fromId, app, id, true, "pro", false);
        //文本文件
        conreviewHandler.fileremove("conapplicationApp", fromId, app, id, false, "", false);
        //flowCommonController.completeFlow(app,id,op,objmap);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 校验成本是否满足合同申请
     *
     * @param map
     * @return
     */
    private String validateCost(Map<String, Object> map) throws Exception {
        // 组织成本属性对象
        CostAttribute costAttribute = combineCostAttribute(map);
        // 校验成本是否满足合同申请
        return costOccupyService.judgeCostEnough(costAttribute);
    }

    /**
     * 组织成本属性对象
     *
     * @param map
     * @return
     */
    private CostAttribute combineCostAttribute(Map<String, Object> map) {
        CostAttribute costAttribute = new CostAttribute();
        costAttribute.setProId(MapUtils.getInteger(map, "proid"));
        costAttribute.setCostItemId(MapUtils.getInteger(map, "pbid"));
        costAttribute.setOccupyCost(new BigDecimal(MapUtils.getString(map, "totalprice")));
        return costAttribute;
    }

    //合同申请审批完之后，添加到合同台账
    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        //如果是服务采购，修改status状态
        if ("approval0201".equals(flowNode.getId()) && op.isFlag()) {
            List<Map<String, Object>> list = handlerService.findBySql("select contracttype  from gq_conapplication where id=" + id);
            if (!"生产外协合同".equals(list.get(0).get("contracttype")) && !"科研外协合同".equals(list.get(0).get("contracttype"))) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", id);
                map.put("status", "行政负责人待审批");
                handlerService.update("gq_conapplication", map);
            }
        }
    }

    //    @Override
    public void afterCloseFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        // 组织成本属性对象
        CostAttribute costAttribute = combineCostAttribute(op.getVariables());
        // 调用成本占用方法
        costOccupyService.costOccupyRelease(costAttribute, false);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //流程审批过程中，添加子表数据后，需要将创建人改成主表中的创建人，便于主表创建人能够查到到子表数据
        if ("gq_expertgroup".equals(objName)) {
            //获取主表主键id,查询主表创建人，修改子表创建人
            String conid = MapUtils.getString(data, "conid");
            List<Map<String, Object>> list = handlerService.findBySql("select createuser,createuserdesc,deptcode from gq_conapplication where conid = " + conid);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> paymap : list) {
                    String createuser = MapUtils.getString(paymap, "createuser");
                    String createuserdesc = MapUtils.getString(paymap, "createuserdesc");
                    String deptcode = MapUtils.getString(paymap, "deptcode");
                    int id = MapUtils.getIntValue(data, "id");
                    String upd = "update gq_expertgroup set createuser = '" + createuser + "',createuserdesc = '" + createuserdesc + "',deptcode = '" + deptcode + "' where id = " + id;
                    handlerService.updateBySql(upd);
                }
            }

        }
        if ("gq_conapplication".equals(objName) && !isUpdate) {
            //合同申请保存后，根据选择的合同类型，对应到合同模板，自动生成合同文本，调用生成合同接口
            Map<String, Object> map = new HashMap<>();
            map.put("conname", data.get("conname"));
            map.put("id", data.get("id"));
            String contemplate = "1117";
            if (ToolUtil.isNotEmpty(data.get("contemplate"))) {
                contemplate = (String) data.get("contemplate");
            }
            map.put("contemplate", contemplate);
            try {
                poiController.tmpGenerate(map, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //给文件列表自动赋值
            try {
                conUtil.setlistfile(MapUtils.getIntValue(data, "id"), app, MapUtils.getIntValue(data, "conid"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //保持后，如何是子合同，自动把框架合同的对方单位名称带过来，还是说子合同不需要选择对方单位名称
        //查询框架合同签订信息中，对方单位名称，添加到对方单位名称子表
        if ("是".equals(data.get("isconsign"))) {
            Map<String, Object> map = handlerService.findOneBySql("select supplierno,oppcompany from gq_consigns where concode = '" + data.get("maincon") + "'");
            String supplierno = MapUtils.getString(map, "supplierno");
            if (ToolUtil.isNotEmpty(supplierno)) {
                Map<String, Object> map1 = handlerService.findOneBySql("select * from gq_coordinationinfo where supplierno  = '" + supplierno + "'");
                if(map1!=null){
                    map1.put("conid", data.get("conid"));
                    handlerService.updateBySql("delete from gq_coordinationinfo where conid = " + data.get("conid"));
                    handlerService.insert("gq_coordinationinfo", map1);
                }

            }
        }

        //物料详情保存后，将含税金额汇总统计到合同金额
        if ("gq_conpoline".equals(objName)) {
            Map<String, Object> map = handlerService.findOneBySql("select sum(totalcost) as totalcosts  from gq_conpoline where conid =" + data.get("conid") + " and conpid = " + data.get("conpid"));
            if (map != null) {
                String totalprice = MapUtils.getString(map, "totalcosts");
                handlerService.updateBySql("update gq_conapplication set totalprice =" + totalprice + "  where id =" + data.get("conpid"));
            }
        }


    }

    //将信息添加到公示表中
    public void setNotice(String title, Date endTime, String content) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("tittle", title);
        map.put("content", content);
        map.put("endtime", endTime);
        map.put("createuser", 1);
        map.put("deptid", "BL");
        map.put("createuserdesc", "超级管理员");
        map.put("updateuser", 1);
        map.put("isshow", 1);
        map.put("status", "未查看");
        Map<String, Object> map2 = new HashMap<>();
        handlerService.addBizNum("noticeApp", "gq_notice", map2);
        map.put("noticenum", map2.get("noticenum"));
        handlerService.insert("gq_notice", map);
    }

    //汇总供方信息
    public String setTwo(long id) {
        //获取合同申请中供方单位子表中的数据，汇总到乙方名称中 关联关系pid=:id
        String sql = "select  companyname from gq_coordinationinfo where pid = " + id;
        List<Map<String, Object>> list2 = handlerService.findBySql(sql);
        StringBuffer sb = new StringBuffer();
        String companynames = "";
        if (CollectionUtils.isNotEmpty(list2)) {
            for (Map<String, Object> stringObjectMap : list2) {
                sb.append(",").append(stringObjectMap.get("companyname"));
            }
            companynames = sb.toString().replaceFirst(",", "");
            String upd = "update gq_conapplication set secondname ='" + companynames + "' where id = " + id;
            handlerService.updateBySql(upd);
        }
        return companynames;
    }

    public String setTwos(long conid, String tableName) {
        //获取合同申请中供方单位子表中的数据，汇总到乙方名称中 关联关系pid=:id
        String sql = "select  companyname from gq_coordinationinfo where conid = " + conid;
        List<Map<String, Object>> list2 = handlerService.findBySql(sql);
        StringBuffer sb = new StringBuffer();
        String companynames = "";
        if (CollectionUtils.isNotEmpty(list2)) {
            for (Map<String, Object> stringObjectMap : list2) {
                sb.append(",").append(stringObjectMap.get("companyname"));
            }
            companynames = sb.toString().replaceFirst(",", "");
            String upd = "update " + tableName + " set secondname ='" + companynames + "' where conid = " + conid;
            handlerService.updateBySql(upd);
        }
        return companynames;
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_conpoline".equals(objName)) {
            //框架合同才需要设置未接收数和未订货数，用于子合同的控制
            Map<String, Object> map = handlerService.findOneBySql("select isframecon from gq_conapplication where id = " + data.get("conpid"));
            if ("是".equals(map.get("isframecon"))) {
                data.put("unordered", data.get("orderqty"));//待订货数
            }
            //所有合同都要有待接收数，不然，采购接收的时候无法选择到
            data.put("unreceivedqty", data.get("orderqty"));//待接收数
            data.put("unpaidamts", data.get("totalcost"));//未付金额
            //data.put("arrquantity",data.get("orderqty"));//到货数

        }
        if ("gq_conapplication".equals(objName) && "是".equals(data.get("isframecon"))) {
            data.put("untotalprice", data.get("totalprice"));//可分配金额
        }
        //已做统一处理
//        if ("gq_conapplication".equals(objName)) {
//            data.put("conname", MapUtils.getString(data, "conname").replace("'", "\""));
//        }
        if ("gq_conapplication".equals(objName) && ToolUtil.isNotEmpty(data.get("maincon")) && "否".equals(data.get("isframecon"))) {
            //框架合同可分配金额，等于框架合同金额，减去所有提交的，跟它相关的子合同金额之和
            String maincon = MapUtils.getString(data, "maincon");

            Map<String, Object> maincons = null;
            if (ToolUtil.isEmpty(data.get("id"))) {
                maincons = handlerService.findOneBySql("select sum(totalprice) as totalprices from gq_conapplication where maincon = '" + maincon + "' and status not in ('新建','已作废')");
            } else {
                maincons = handlerService.findOneBySql("select sum(totalprice) as totalprices from gq_conapplication where maincon = '" + maincon + "' and status not in ('新建','已作废') and id!=" + data.get("id"));
            }
            float totalprices = 0;//子合同已使用
            if (maincons != null && ToolUtil.isNotEmpty(maincons.get("totalprices"))) {
                totalprices = MapUtils.getFloatValue(maincons, "totalprices");
            }
            //框架合同金额
            float maintotalprice = MapUtils.getFloatValue(data, "maintotalprice");
            float untotalprice = maintotalprice - totalprices;//框架合同剩余金额

            float totalprice = MapUtils.getFloatValue(data, "totalprice");
            //float untotalprice = MapUtils.getFloatValue(data,"untotalprice");
            if (totalprice > untotalprice) {
                throw new ServiceException("子合同金额不能超过框架合同剩余分配金额，剩余金额：" + untotalprice);
            }
        }

        super.beforSave(app, objName, data, isUpdate);
    }
}
